package com.bill.common.system.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.bill.common.system.dao.IExtractDAO;
import com.bill.common.system.dao.ITransactionRecordDAO;
import com.bill.common.system.dto.ExtractDTO;
import com.bill.common.system.dto.RuleDTO;
import com.bill.common.system.entity.Extract;
import com.bill.common.system.entity.TransactionRecord;
import com.bill.common.user.dao.IAccountDAO;
import com.bill.common.user.dao.IRegisterUserDAO;
import com.bill.common.user.dto.RegisterUserDTO;
import com.bill.common.user.entity.Account;
import com.bill.common.user.entity.RegisterUser;
import com.bill.common.user.service.IRegisterUserService;
import com.bill.common.utils.DoubleFormat;
import com.bill.common.utils.TranType;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.util.StringUtils;

public class ExtractService implements IExtractService {
	@Autowired
	private IExtractDAO extractDAO;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IRegisterUserService registerUserService;
	@Autowired
	private IAccountDAO accountDAO;
	@Autowired
	private ITransactionRecordDAO transactionRecordDAO;
	@Autowired
	private IRuleService ruleService;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Transactional
	public PageDTO findPager(ExtractDTO qdto, int start, int limit,
			 String sord,String sidx) {
		// TODO Auto-generated method stub
		PageDTO p = extractDAO.findPager(qdto, start, limit, sord, sidx);
		List<Extract> lists = (List<Extract>)p.getData();
		List<ExtractDTO> list = new ArrayList<ExtractDTO>();
		for(Extract entity:lists){
			ExtractDTO dto = new ExtractDTO();
			dto.entity2dto(entity, dto);
			list.add(dto);
		}
		p.setData(list);
		return p;
	}
	
	@Transactional
	public String apply(ExtractDTO dto) {
		RegisterUser user = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		if(user!=null){
			RegisterUserDTO registerUserDTO = new RegisterUserDTO(dto.getLoginName(),
					dto.getPasswordProblem(), dto.getPasswordAnswer());
			/*if (!registerUserService.checkPwdProblem(registerUserDTO)) {//验证密保是否正确
				return "Secret answer is not correct(密保答案不正确)!";
			}*/
			//判断当天是否已提现申请
			if(transactionRecordDAO.todayIsRecordUseTiXian(dto.getLoginName(), TranType.TiXian)){
				return "Mention now failed, to mention only a day now, thank you!(提现失败，每天只允许提现一次，谢谢!)";
			}
			
			/*if(extractDAO.todayIsTiXian(dto.getLoginName())){
				return "提现失败，每天只允许提现一次，谢谢!";
			}*/
			String loginName = dto.getLoginName();
			
			//Map<String,Double> maps = ruleService.findRuleMap(new String[]{"TXA","TXB","StaticTxDate"});
			Double valus = 0D;
//			RegisterUser ru = registerUserDAO.findUniqueBy("loginName", loginName);
//			if("1000".equals(ru.getRegisterLevel())){
//				valus = ruleDTO.getRule013().doubleValue();
//			}else{
//				valus = ruleDTO.getRule014().doubleValue();
//			}
//			if("DaozhangTimeItem1".equals(dto.getDaozhangTime())){
//				valus = ruleDTO.getRule012().doubleValue();
//			}else if("DaozhangTimeItem2".equals(dto.getDaozhangTime())){
//				valus = ruleDTO.getRule013().doubleValue();
//			}
			valus = ruleDTO.getRule013().doubleValue();
			Double balance = 0D;
			String formAccount = "Static";
			String formAccountStr = "股票钱包提现";
			
			if("Dynamic".equals(dto.getDtype())){
				balance = transactionRecordService.findUserBalance(loginName, "Dynamic");
				formAccount = "Dynamic";
				formAccountStr = "现金币提现";
			}else{
				balance = transactionRecordService.findUserBalance(loginName, "Static");
				/*Calendar cl = Calendar.getInstance();
				cl.setTime(new Date());
//				System.out.println(">>>>>>>::::"+cl.get(Calendar.DAY_OF_MONTH));
				if(cl.get(Calendar.DAY_OF_MONTH)==ruleDTO.getRule012()){
					balance = transactionRecordService.findUserBalance(loginName, "Static");
				}else{
					return "静态分红需要在固定的时间才允许提现，请咨询客服或查看公告!";
				}*/
				
			}
			
			
			
			if(balance<dto.getTixiangSum()){
				return "提现金额大于可提现金额!";//提现金额大于可提现金额!
			}else{
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(loginName);
				tr.setTransactionObject("system");
				tr.setTransactionType(TranType.TiXian);
				tr.setRemark(formAccountStr);
				transactionRecordService.updateTran(tr, dto.getDtype(), (dto.getTixiangSum()*(100-valus))/100, "CUT");
				
				
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(loginName);
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.TiXianShouXuFei);
				tr1.setRemark(formAccountStr);
				transactionRecordService.updateTran(tr1, dto.getDtype(), (dto.getTixiangSum()*valus)/100, "CUT");
				
				Extract entity = new Extract();
				ExtractDTO.dto2entity(dto, entity);
				entity.setStatus("待受理");
				entity.setAccountType(user.getAccountType());
				entity.setBankAccount(user.getBankAccount());
				entity.setAccountName(user.getUserName());
				entity.setOpenBankAddress(user.getOpenBankAddress());
				entity.setFormAccount(formAccount);
				entity.setFormAccountStr(formAccountStr);
				entity.setPoundage((dto.getTixiangSum()*valus)/100);
				entity.setCreateTime(new Date());
				entity.setBalance(DoubleFormat.format(balance-dto.getTixiangSum()));
				extractDAO.save(entity);
			}
		}else{
			return "提现会员不存在，请检查!";//申请的会员不存在!
		}
		
		return "提现成功，财务会尽快受理，提现手续费："+ruleDTO.getRule013().longValue()+"%";//"申请成功，财务会尽快受理!"
	}
	/**
	 * 子帐户提现
	 * @param dto
	 * @return
	 */
	public String subAccountApply(ExtractDTO dto){
		String loginName = dto.getLoginName(); 
		// TODO Auto-generated method stub
		RegisterUser user = registerUserDAO.findUniqueBy("loginName", loginName);
		if(user!=null){
			//判断当天是否已提现申请
			/*if(transactionRecordDAO.todayIsRecord(loginName, TranType.TiXian)){
				return "提现失败，每天只允许提现一次，谢谢!";
			}*/
			String parentAccount = user.getParentAccount();
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			Double valus = 0D;
			valus = ruleDTO.getRule013().doubleValue();
			Double balance = transactionRecordService.findUserBalance(loginName, "Dynamic");;
			String formAccount = "Dynamic";
			String formAccountStr = "子账户提现";
			
			if(balance<dto.getTixiangSum()){
				return "提现金额大于可提现金额!";//提现金额大于可提现金额!
			}else{
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(loginName);
				tr.setTransactionObject("system");
				tr.setTransactionType(TranType.TiXian);
				tr.setRemark(formAccountStr);
				transactionRecordService.updateTran(tr, "Dynamic", (dto.getTixiangSum()*(100-valus))/100, "CUT");
				
				
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(loginName);
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.TiXianShouXuFei);
				tr1.setRemark(formAccountStr);
				transactionRecordService.updateTran(tr1, "Dynamic", (dto.getTixiangSum()*valus)/100, "CUT");
				
				Extract entity = new Extract();
				ExtractDTO.dto2entity(dto, entity);
				entity.setStatus("待受理");
				entity.setAccountType(user.getAccountType());
				entity.setBankAccount(user.getBankAccount());
				entity.setAccountName(user.getUserName());
				entity.setOpenBankAddress(user.getOpenBankAddress());
				entity.setFormAccount(formAccount);
				entity.setFormAccountStr(formAccountStr);
				entity.setPoundage((dto.getTixiangSum()*valus)/100);
				entity.setCreateTime(new Date());
				entity.setBalance(DoubleFormat.format(balance-dto.getTixiangSum()));
				entity.setParentAccount(parentAccount);
				entity.setRemark("");
				extractDAO.save(entity);
			}
		}else{
			return "提现会员不存在，请检查!";//申请的会员不存在!
		}
		
		return "提现成功，财务会尽快受理!";//"申请成功，财务会尽快受理!"
	}
	
	@Transactional
	public void delete(Long id) {
		// TODO Auto-generated method stub
		Extract entity = extractDAO.findById(id);
		RegisterUser user = registerUserDAO.findUniqueBy("loginName", entity.getLoginName());
		Account ac = user.getAccount();
		ac.setBalance(DoubleFormat.format(ac.getBalance()+entity.getTixiangSum()));
		accountDAO.merge(ac);
		//保存历史记录
		transactionRecordDAO.save(new TransactionRecord(entity.getLoginName(), 
				entity.getLoginName(), 
				"提现取消", 
				entity.getTixiangSum(),
				new Date(), 
				"提现取消"));
		
		extractDAO.delete(entity);
		
	}
	@Transactional
	public void confirm(ExtractDTO dto) {
		// TODO Auto-generated method stub
		Extract entity = extractDAO.findById(dto.getId());
		entity.setHandTime(new Date());
		entity.setStatus(dto.getStatus());
		entity.setRemark(dto.getRemark());
		//拒绝后退回相应的账户
		if("拒绝".equals(dto.getStatus())){
			TransactionRecord tr1 = new TransactionRecord();
			tr1.setLoginName(entity.getLoginName());
			tr1.setTransactionObject("system");
			tr1.setTransactionType(TranType.JuJueTiXianTuiHui);
			transactionRecordService.updateTran(tr1, entity.getFormAccount(), entity.getTixiangSum(), "ADD");
		}
		
		extractDAO.merge(entity);
		
	}
	
	//提现统计
	@Transactional
	public Integer extractCount(String status){
		return extractDAO.extractCount(status);
	}
	
	
	
	
	

}
